package com.leetcode.algorithm.y22.m07.w4;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.leetcode.algorithm.common.NestedInteger;

/**
 * 341. 扁平化嵌套列表迭代器
 * 
 * https://leetcode.cn/problems/flatten-nested-list-iterator/
 * 
 * @author jie.deng
 *
 */
public class NestedIterator implements Iterator<Integer> {

	private List<Integer> list;
	private Iterator<Integer> iterator;

	public NestedIterator(List<NestedInteger> nestedList) {
		list = new ArrayList<>();
		dfs(nestedList, list);
		iterator = list.iterator();
	}

	private void dfs(List<NestedInteger> nestedList, List<Integer> list) {
		for (NestedInteger nestedInteger : nestedList) {
			if (nestedInteger.isInteger()) {
				list.add(nestedInteger.getInteger());
			} else {
				dfs(nestedInteger.getList(), list);
			}
		}
	}

	@Override
	public Integer next() {
		return iterator.next();
	}

	@Override
	public boolean hasNext() {
		return iterator.hasNext();
	}

}